<template>
  <view class="content">
    <!-- 导航栏 -->
    <van-nav-bar
      title="附近的停车场"
      left-text="返回"
      :left-arrow="true"
      @click-left="onClickLeft"
    />

    <!-- 搜索框 -->
    <view class="search-container">
      <van-search
        v-model="searchValue"
        placeholder="搜索停车场"
        :show-action="true"
        @search="onSearch"
        @cancel="onCancel"
      >
        <view slot="action" @tap="onSearch">搜索</view>
      </van-search>
    </view>

    <!-- 地图容器 -->
    <view class="map-container">
      <map
        id="map"
        class="map"
        :latitude="latitude"
        :longitude="longitude"
        :markers="markers"
        :scale="16"
        :skew="40"
        :enable-3D="true"
        :enable-building="true"
        :enable-overlooking="true"
        :rotate="0"
        show-location
        layer-style="1"
        @markertap="onMarkerTap"
      ></map>
    </view>

    <!-- 定位按钮 -->
    <view class="location-button" @click="handleReLocate">
      <text class="icon">&#xe666;</text>
    </view>

    <!-- 停车场详情弹出层 -->
    <van-popup
      v-model:show="showStationDetail"
      position="left"
      :style="{ width: '80%', height: '100%' }"
    >
      <view class="station-detail">
        <view class="station-detail-header">
          <text>{{ selectedStation ? selectedStation.title : '' }}</text>
          <text class="icon" @tap="showStationDetail = false">&#xe6a7;</text>
        </view>
        <view class="station-detail-content">
          <view class="detail-item">
            <text class="icon">&#xe6d9;</text>
            <text>{{ selectedStation ? selectedStation.address : '' }}</text>
          </view>
          <view class="detail-item">
            <text class="icon">&#xe74c;</text>
            <text>距离：{{ selectedStation ? selectedStation.distance : 0 }}公里</text>
          </view>
          <view class="detail-item">
            <text class="icon">&#xe68f;</text>
            <text>营业时间：24小时</text>
          </view>
          <view class="detail-item">
            <text class="icon">&#xe71f;</text>
            <text>剩余车位：{{ selectedStation ? selectedStation.spaces : 0 }}个</text>
          </view>
          <view class="detail-actions">
            <van-button type="primary" block @click="startNavigation">开始导航</van-button>
          </view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script>
import QQMapWX from '@/utils/qqmap-wx-jssdk.min.js';

export default {
  data() {
    return {
      searchValue: '',
      selectedStation: null,
      currentPosition: null,
      mapContext: null,
      qqmapsdk: null,
      showStationDetail: false,
      markers: [],
      qqMapKey: 'DGLBZ-B2PWJ-6DEFK-DSJHB-5C72Z-F6FCK', // 替换成你自己申请的有效key
      cachedResults: {}, // 用于缓存搜索结果
      cacheExpireTime: 5 * 60 * 1000, // 缓存有效期：5分钟
    }
  },

  computed: {
    latitude() {
      return this.currentPosition ? this.currentPosition.latitude : 39.908860;
    },
    longitude() {
      return this.currentPosition ? this.currentPosition.longitude : 116.397390;
    }
  },

  methods: {
    onClickLeft() {
      uni.navigateBack();
    },

    handleReLocate() {
      this.startGeolocation();
    },

    initMap() {
      try {
        if (!this.qqMapKey) {
          throw new Error('未配置腾讯地图密钥');
        }
        
        // 实例化腾讯地图SDK
        this.qqmapsdk = new QQMapWX({
          key: this.qqMapKey
        });

        // 测试SDK是否正常初始化
        this.qqmapsdk.search({
          keyword: '测试',
          success: () => {
            console.log('腾讯地图SDK初始化成功');
          },
          fail: (error) => {
            console.error('腾讯地图SDK测试失败:', error);
            throw new Error(error.message);
          }
        });
        
        this.mapContext = uni.createMapContext('map', this);
        this.startGeolocation();
        
      } catch (error) {
        console.error('地图初始化失败:', error);
        uni.showToast({
          title: '地图初始化失败：' + error.message,
          icon: 'none',
          duration: 3000
        });
      }
    },

    startGeolocation() {
      uni.showLoading({
        title: '正在定位...',
        mask: true
      });

      // 先获取高精度定位
      uni.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        highAccuracyExpireTime: 3000,
        success: (res) => {
          console.log('定位成功:', res);
          // 立即更新当前位置标记
          this.markers = [{
            id: 0,
            latitude: res.latitude,
            longitude: res.longitude,
            width: 12,
            height: 12,
            backgroundColor: '#1989FA',  // 蓝色当前位置
            anchor: { x: 0.5, y: 0.5 },
            callout: {
              content: '当前位置',
              color: '#FFFFFF',
              fontSize: 14,
              borderRadius: 4,
              bgColor: '#1989FA',
              padding: 8,
              display: 'ALWAYS'
            }
          }];

          // 更新位置并移动地图
          this.setCurrentPosition({
            latitude: res.latitude,
            longitude: res.longitude
          });
        },
        fail: (error) => {
          console.error('定位失败:', error);
          uni.showToast({
            title: '定位失败，请检查定位权限',
            icon: 'none'
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },

    setCurrentPosition(location) {
      this.currentPosition = location;
      
      // 更新地图中心点并设置倾斜角度
      this.mapContext.moveToLocation({
        latitude: location.latitude,
        longitude: location.longitude,
        success: () => {
          // 搜索附近停车场
          this.searchNearbyParking(location);
        }
      });
    },

    searchNearbyParking(location) {
      // 检查网络状态
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType === 'none') {
            uni.showToast({
              title: '请检查网络连接',
              icon: 'none'
            });
            return;
          }

          // 检查缓存
          const cacheKey = `${location.latitude},${location.longitude}`;
          const cachedData = this.getCachedData(cacheKey);
          
          if (cachedData) {
            this.updateMarkers(location, cachedData);
            return;
          }

          // 显示加载提示
          uni.showLoading({
            title: '搜索中...',
            mask: true
          });

          // 使用腾讯地图 API 搜索
          this.qqmapsdk.search({
            keyword: '停车场',
            location: `${location.latitude},${location.longitude}`,
            radius: 50000,  // 搜索半径改为50公里
            page_size: 50,  // 增加返回结果数量
            auto_extend: 1, // 自动扩大搜索范围
            success: (res) => {
              uni.hideLoading();
              const { data } = res;
              if (data && data.length > 0) {
                this.cacheData(cacheKey, data);
                this.updateMarkers(location, data);
                
                // 显示找到的停车场数量
                uni.showToast({
                  title: `找到${data.length}个停车场`,
                  icon: 'none',
                  duration: 2000
                });
              } else {
                uni.showToast({
                  title: '附近50公里没有找到停车场',
                  icon: 'none'
                });
              }
            },
            fail: (error) => {
              uni.hideLoading();
              console.error('搜索失败:', error);
              uni.showToast({
                title: '搜索失败，请稍后重试',
                icon: 'none'
              });
            }
          });
        }
      });
    },

    updateMarkers(location, data) {
      // 保持当前位置标记
      const currentLocationMarker = {
        id: 0,
        latitude: location.latitude,
        longitude: location.longitude,
        width: 16,
        height: 16,
        zIndex: 100,
        // 使用圆点替代图标
        callout: {
          content: '当前位置',
          color: '#FFFFFF',
          fontSize: 14,
          borderRadius: 4,
          bgColor: '#1989FA',
          padding: 8,
          display: 'ALWAYS'
        }
      };

      // 合并当前位置标记和停车场标记
      this.markers = [
        currentLocationMarker,
        ...data.map((item, index) => ({
          id: index + 1,
          latitude: parseFloat(item.location.lat),
          longitude: parseFloat(item.location.lng),
          width: 20,
          height: 20,
          // 使用圆点替代图标
          callout: {
            content: item.title,
            color: '#333333',
            fontSize: 12,
            borderRadius: 4,
            bgColor: '#FFFFFF',
            padding: 4,
            display: 'ALWAYS'
          }
        }))
      ];

      // 调整地图视野以包含所有标记
      if (data.length > 0) {
        setTimeout(() => {
          this.mapContext.includePoints({
            points: this.markers,
            padding: [50, 50, 50, 50]
          });
        }, 500);
      }
    },

    cacheData(key, data) {
      this.cachedResults[key] = {
        data: data,
        timestamp: Date.now()
      };
    },

    getCachedData(key) {
      const cached = this.cachedResults[key];
      if (!cached) return null;
      
      // 检查缓存是否过期
      if (Date.now() - cached.timestamp > this.cacheExpireTime) {
        delete this.cachedResults[key];
        return null;
      }
      
      return cached.data;
    },

    onSearch() {
      if (!this.searchValue) {
        uni.showToast({
          title: '请输入搜索关键词',
          icon: 'none'
        });
        return;
      }

      // 显示加载提示
      uni.showLoading({
        title: '搜索中...'
      });

      // 使用 POI 搜索接口
      this.qqmapsdk.search({
        keyword: this.searchValue + ' 停车场',  // 添加停车场关键词
        boundary: 'nearby(' + this.currentPosition.latitude + ',' + this.currentPosition.longitude + ',10000)',  // 搜索半径10公里
        page_size: 20,
        success: (res) => {
          console.log('搜索结果:', res);
          const { data } = res;
          if (data && data.length > 0) {
            const location = data[0].location;
            // 移动地图到搜索结果位置
            this.mapContext.moveToLocation({
              latitude: location.lat,
              longitude: location.lng,
              success: () => {
                // 更新地图标记
                this.updateMarkers(this.currentPosition, data);
              },
              fail: (error) => {
                console.error('移动地图失败:', error);
                uni.showToast({
                  title: '移动地图位置失败',
                  icon: 'none'
                });
              }
            });
          } else {
            uni.showToast({
              title: '未找到相关停车场',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('搜索失败:', error);
          uni.showToast({
            title: error.message || '搜索失败，请检查网络连接',
            icon: 'none',
            duration: 2000
          });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    },

    onCancel() {
      // 实现取消搜索的逻辑
    },

    onMarkerTap(e) {
      const { markerId } = e.detail;
      if (markerId === 0) return;

      const marker = this.markers[markerId];
      if (marker) {
        const [title, distance] = marker.callout.content.split('\n');
        const parkingData = this.getCachedData(`${this.currentPosition.latitude},${this.currentPosition.longitude}`);
        const parkingInfo = parkingData[markerId - 1];

        this.selectedStation = {
          title: parkingInfo.title,
          address: parkingInfo.address,
          distance: distance.split(':')[1].trim(),
          latitude: marker.latitude,
          longitude: marker.longitude,
          tel: parkingInfo.tel,
          category: parkingInfo.category,
          spaces: Math.floor(Math.random() * 100) // 由于API不提供车位信息，仍使用模拟数据
        };
        this.showStationDetail = true;
      }
    },

    startNavigation() {
      if (!this.selectedStation) return;
      
      const { latitude, longitude, title, address } = this.selectedStation;
      
      uni.showModal({
        title: '导航方式',
        content: '请选择导航方式',
        confirmText: '导航',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 使用微信内置导航
            uni.openLocation({
              latitude: parseFloat(latitude),
              longitude: parseFloat(longitude),
              name: title,
              address: address || '停车场地址',
              scale: 18
            });
          }
        }
      });
    },

    // 添加网络状态监听
    onShow() {
      uni.onNetworkStatusChange((res) => {
        if (!res.isConnected) {
          uni.showToast({
            title: '网络连接已断开',
            icon: 'none'
          });
        }
      });
    }
  },

  onLoad() {
    this.initMap();
  },

  onUnmounted() {
    if (this.map) {
      this.map = null;
    }
  }
}
</script>

<style>
.content {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
}

.search-container {
  position: relative;
  z-index: 100;
}

.map-container {
  position: absolute;
  top: 88px;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #f6f6f6;
}

.map {
  width: 100%;
  height: 100%;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.location-button {
  position: fixed;
  bottom: 30px;
  right: 20px;
  width: 40px;
  height: 40px;
  background-color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 100;
}

.location-button .icon {
  font-size: 24px;
  color: #1989fa;
}

/* 其他样式保持不变... */

/* 隐藏百度地图版权信息 */
:deep(.BMap_cpyCtrl) {
  display: none;
}

:deep(.anchorBL) {
  display: none;
}

:deep(.BMapLabel) {
  border: none !important;
  background: none !important;
}

/* 添加字体图标样式 */
@font-face {
  font-family: 'vant-icon';
  src: url('/static/fonts/vant-icon.woff2') format('woff2');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
}

.van-icon {
  font-family: 'vant-icon' !important;
}

.icon {
  font-family: 'vant-icon';
  font-size: 24px;
  color: #1989fa;
}

.station-detail-header .icon {
  color: #999;
}

.detail-item .icon {
  margin-right: 8px;
}
</style>
